/** 页面公共普通方法（不包含async的网络请求） 
 * @property {reloadFn} 页面重载函数
 * @property {backFn} 后退函数
 * @property {wxShareFn} H5微信分享页面
 * @property {addUrlParam} 给URL增加指定参数，一般用于给web-view页面链接增加强制退出参数forcelogout=1 
 * 小程序原生的storage数据被清后，web-view中的登录cookie并不会同步清除，这样会出现原生页面没有登录，web-view是登录状态
 * 注：一般用于跳转链接处理
 * @property {encodeUrl} 加密url
 * 注:一般用于接口请求，处理请求地址
 * @property {pageFn} 页面调整平台切换处理（具体使用方法请在/pages/packages/article/index/index内搜索articlePage）
 * @property {linkTo} 全平台跳转，凡是涉及到多平台兼容跳转，直接可以调用这个方法
 * 注：发布页列表跳转到对应模块详情页，window.channelDomain是undefined
 * 安卓跳转原生appLinkConfig的molude和templates必传
 * @property {tologin} 全平台判断登录跳转---不传path默认登录成功刷新当前页面
 * @property {openMap} 全平台兼容打开地图
 * @property {previewImage} 全平台兼容图片预览 data格式：{app:{urls:[],current:链接},init:{urls:[],current:下标}}
 * @property {iosShare} ios分享配置
 * @property {posterProcess} 海报富文本处理,只用传字符串就行
 * @property {getMapUrl} H5打开地图要跳转的URL，代替uni.openLocation方法
 * @property {isValidTimestamp} 判断是否为合法时间戳 创建 
 * @property {dateFormatter} Intl.DateTimeFormat 对象并设置格式选项
 * @property {transTimes} 转换PHP时间戳
 * @property {timestampToTime} 时间戳转换（直接传值调用）
 * @property {loginCheck} 登录验证，返回true表示登录成功，直接if(app.loginCheck()){}
 * @property {showErr} 显示提示框
 * @property {biasTop} 顶部偏差计算(element:元素选择器类名,顶部元素)
 * @property {getdomFn} 选项式API获取元素节点信息
 * @property {getdomComposition} 组合式API获取元素节点信息
 * @property {callPhone} 拨打电话
 * @property {useOtherPhoneNumber} 获取手机号码并绑定给当前用户
 * @property {getFonts} 远程加载字体资源
 * @property {cachePage} 指定模块首页缓存，必须要cityid
 * @property {confirmLoaction} 全平台获取本地位置信息
 * @property {drawAdv} 广告渲染
 * pageThis:页面的this,adv:广告数据,advId渲染的容器ID
 * @property {base64src} 图片base64转src
 * @property {chatIntervalTime} 聊天间隔时间
 * 具体使用说明详见定义此函数的地方
*/
export default {
    reloadFn(url) {
        let pages = getCurrentPages();
        // 声明一个pages使用getCurrentPages方法
        let currPage = pages[pages.length - 1];
        //关闭当前页面，跳转到当前页面
        uni.redirectTo({
            url: decodeURIComponent(url ? url : currPage.$page.fullPath) //防止数据被转码
        });
    },
    backFn(miniFailUrl, webFailUrl) {
        if (this.globalData.appBoolean) { //APP
            window.setupWebViewJavascriptBridge(function (bridge) {
                bridge.callHandler("goBack", {}, function (responseData) { });
            })
            return false
        } else {
            let canNavBack = getCurrentPages();
            if (canNavBack && canNavBack.length > 1) {
                uni.navigateBack({
                    delta: 1
                });
            } else if (this.globalData.platForm == 'web') { //H5
                // if(webFailUrl){
                // 	location.href = webFailUrl;
                // }else{}
                history.back();
            } else { //小程序
                uni.redirectTo({
                    url: miniFailUrl,
                    fail: function () {
                        uni.reLaunch({
                            url: '/pages/index/index'
                        })
                    }
                })
            }
        }
    },
    wxShareFn({
        title = '',
        description = '',
        link = '',
        imgUrl = '',
        AppMessage = {}, //下面自定义分享配置（优先级更高）
        Timeline = {},
        ShareQQ = {},
        ShareWeibo = {},
        ShareQZone = {}
    }) {
        if (this.globalData.platForm != 'web') {
            return false
        }
        if (!link) {
            let url = window.location.href;
            let fromShare = this.globalData.userid ? 'fromShare=' + this.globalData.userid : '';
            link = `${url}${url.includes('?') ? '&' : '?'}${fromShare}`;
        }
        //分享配置
        let config = JSON.parse(JSON.stringify(window.wxconfig));
        config['title'] = title || config['title'] || '';
        config['description'] = description || config['description'] || '';
        config['link'] = link || config['link'];
        config['imgUrl'] = imgUrl || config['imgUrl'] || '';
        if (wxBoolean) {
            jWeixin.ready(function () {
                jWeixin.onMenuShareAppMessage({
                    title: AppMessage.title || config.title,
                    desc: AppMessage.description || config.description,
                    link: AppMessage.link || config.link,
                    imgUrl: AppMessage.imgUrl || config.imgUrl,
                });
                jWeixin.onMenuShareTimeline({
                    title: Timeline.title || config.title,
                    link: Timeline.link || config.link,
                    imgUrl: Timeline.imgUrl || config.imgUrl,
                });

                // 新增 分享至朋友圈
                window.jWeixin.updateAppMessageShareData({
                    title: config.title,
                    desc: config.description,
                    link: config.link,
                    imgUrl: config.imgUrl,
                }) //自定义微信分享给朋友
                window.jWeixin.updateTimelineShareData({ //自定义分享朋友圈
                    title: Timeline.title || config.title,
                    link: Timeline.link || config.link,
                    imgUrl: Timeline.imgUrl || config.imgUrl,
                    success: (res => { })
                }); //自定义微信分享给朋友


                jWeixin.onMenuShareQQ({
                    title: ShareQQ.title || config.title,
                    desc: ShareQQ.description || config.description,
                    link: ShareQQ.link || config.link,
                    imgUrl: ShareQQ.imgUrl || config.imgUrl,
                });
                jWeixin.onMenuShareWeibo({
                    title: ShareWeibo.title || config.title,
                    desc: ShareWeibo.description || config.description,
                    link: ShareWeibo.link || config.link,
                    imgUrl: ShareWeibo.imgUrl || config.imgUrl,
                });
                jWeixin.onMenuShareQZone({
                    title: ShareQZone.title || config.title,
                    desc: ShareQZone.description || config.description,
                    link: ShareQZone.link || config.link,
                    imgUrl: ShareQZone.imgUrl || config.imgUrl,
                });
            });
            jWeixin.error(function (error) { //错误信息
                console.log(`分享设置失效原因：${error.errMsg}`);
            })
        };
    },
    addUrlParam(url, param = '') {
        if (this.globalData.platForm == 'web' || !url.includes('http')) { //h5不执行或者非外部链接
            return url
        }
        url = decodeURIComponent(url).replace('?', '&'); //先把问号替换成&
        if (!url.match(/cityid=/i)) {
            url += `&cityid=${this.globalData.cityInfo.cityid}`;
        }
        let access_token = uni.getStorageSync('access_token');
        if (access_token && !url.includes('forcelogout=1')) { //如果已经登录添加toke信息
            if (!url.includes('wxMiniProgramLoginByToken=1')) {
                url += '&wxMiniProgramLoginByToken=1';
            }
            if (!url.includes('access_token=')) {
                url += `&access_token=${access_token}`;
            }
        } else { //如果小程序已经退出，强制h5退出
            if(!url.includes('forcelogout=1')){
                url += '&forcelogout=1';
            }
        }

        url = url.replace('&', '?'); //把最左侧的第一个&替换成?
        return url;
    },
    encodeUrl(prarm) {
        if (this.globalData.cityInfo && this.globalData.cityInfo.cityid && prarm && prarm.indexOf(
            '&cityid=') <= -1) {
            prarm += `&cityid=${this.globalData.cityInfo.cityid}`;
        }
        if (this.globalData.platForm == 'web') { //h5不执行
            return prarm
        }
        try {
            var cityInfo = uni.getStorageSync('cityInfo');
            if (cityInfo) {
                this.globalData.cityInfo = cityInfo;
            }

            // console.log(new Date());

            //验证token是否过期
            var nowtime = Date.parse(new Date()) / 1000;
            if (uni.getStorageSync('access_token') && nowtime >= uni.getStorageSync('token_expired')) {
                var res = refreshToken.unit(uni.getStorageSync('refresh_token'), this.globalData.masterDomain,
                    function (datas) {
                        if (datas.state == 100) {
                            // console.log('encodeUrl更新token成功');
                            var access_token = datas.info.access_token;
                            var refresh_token = datas.info.refresh_token;

                            // console.log('更新token：' + new Date());
                            // console.log(datas.info);

                            uni.setStorage({
                                key: 'access_token',
                                data: access_token
                            });
                            uni.setStorage({
                                key: 'refresh_token',
                                data: refresh_token
                            });
                            var token_expired = Date.parse(new Date()) / 1000 + 7200 -
                                20; //两个小时有效期，保险起见，用1小时59分钟40秒
                            uni.setStorage({
                                key: 'token_expired',
                                data: token_expired
                            });
                            this.globalData.access_token = access_token;
                            this.globalData.refresh_token = refresh_token;
                            this.globalData.token_expired = token_expired;
                        } else {
                            console.log('更新失败')
                            //清除缓存数据
                            uni.removeStorage({
                                key: 'userid'
                            });
                            uni.removeStorage({
                                key: 'access_token'
                            });
                            uni.removeStorage({
                                key: 'refresh_token'
                            });
                            uni.removeStorage({
                                key: 'token_expired'
                            });
                            this.globalData.userid = null;
                            this.globalData.access_token = null;
                            this.globalData.refresh_token = null;
                            this.globalData.token_expired = null;

                            // token过期需要跳转登录页面
                            let url;
                            if (this.globalData.loginMode == 1) { //H5 关闭了微信原生登录
                                url = '/pages/redirect/index?url=' + encodeURIComponent(this.addUrlParam(
                                    this.globalData
                                        .masterDomain + '/login.html?from=wxmini&wxMiniProgramLogin=1',
                                    'forcelogout'));
                            } else { //原生
                                url = '/pages/login/index?wxMiniProgramLogin=1';
                            }
                            uni.redirectTo({
                                url: url
                            })
                            return false;


                            // }
                        }
                    });

            }



        } catch (e) {
            console.log('CatchClause', e);
            console.log('CatchClause', e);
        }
        if (prarm) {
            var prarmArr = prarm.split('&');
        } else {
            var prarmArr = [];
        }
        // prarmArr.push('platform_userid=' + (this.globalData.userid ? this.globalData.userid : 0)); //用户ID
        // console.log("最新Token：" + new Date());
        // console.log(wx.getStorageSync('access_token'));

        if (uni.getStorageSync('access_token')) {
            prarmArr.push('access_token=' + encodeURIComponent(uni.getStorageSync(
                'access_token'))); //接口token，由登录成功后接口提供

        }

        // prarmArr.push('accesskey_id=' + this.globalData.accesskey_id); //官网授权的Access Key ID
        // prarmArr = prarmArr.sort(); //不需要排序了
        var stringA = prarmArr.join('&');
        return stringA; //新版本不再需要accesskey和sign，统一使用token的方式传参
    },
    pageFn(importName) {
        if (this.globalData.platForm == 'web') {
            if (process.env.NODE_ENV == 'development') {
                return importName.web.development; //开发环境
            } else {
                // 生产环境中一般是/detail这种  如果出现member/manage 或者bmember/manage 这种情况 择需要跳转个人中心/商家中心的对应页面
                let pathObj = importName.web.production;
                for(let item in pathObj){
                    let path = pathObj[item]
                    let pathArr = path.split('/');
                    let url = path;
                    if(pathArr.length > 1 && pathArr[0]){
                        let defaultUrl = this.globalData.masterDomain + (pathArr[0] == 'member' ? '/u' : '/b')
                        let center_name = pathArr[0] == 'member' ? (this.globalData.appConfig['cfg_user_index'] || defaultUrl) : pathArr[0] == 'bmember' ?  this.globalData.appConfig['cfg_business_index'] : defaultUrl;
                        url = center_name + '/' + pathArr[1];
                    }
                    pathObj[item] = url
                }

                return JSON.parse(JSON.stringify(pathObj)); //生产环境
            }
        } else {
            return importName.mini;
        }
    },
    linkTo(url, redirectb = false, appFullScreen = true, login = false, appLinkConfig = {}) {
        if (login && !this.loginCheck()) { //登录验证
            return false
        }
        if (url) {
            if (this.globalData.platForm == 'web') { //H5
                if (this.globalData.appBoolean) { //APP跳转
                    if (!window.Android && (url.indexOf('work.weixin.qq.com') > -1 || url.includes('tel:'))) {
                        location.href = url.indexOf('work.weixin.qq.com') > -1 ? ('tel:' + this.globalData.siteConfig.hotline) : url
                        return false;
                    }
                    url = `${url.replace('?', '&')}${appFullScreen ? `&${this.globalData.appFullScreen}` : ''}`.replace('&', '?');
                    let appconfig = {};
                    if (window.Android) {
                        appconfig = {
                            'url': url,
                            ...appLinkConfig
                        }
                    } else {
                        appconfig = {
                            'name': '',
                            'code': '',
                            'link': url,
                        }
                    }

                    window.setupWebViewJavascriptBridge(function (bridge) {
                        bridge.callHandler(window.Android ? 'redirectTo' : 'redirectNative', appconfig, function () { });
                    })
                    return false
                } else if (url.indexOf('http') == 0) { //H5原生跳转
                    location.href = decodeURIComponent(url);
                } else { //H5外部链接
                    if (redirectb) {

                        uni.redirectTo({
                            url: url
                        });
                    } else {
                        uni.navigateTo({
                            url: url
                        });
                    }
                }
            } else { //小程序
                if (url.indexOf('work.weixin.qq.com/kfid') > -1) {
                    //小程序跳转客服
                    var link = url.split('?id=')[0];
                    var //客服链接
                        id = url.split('?id=')[1]; //企业ID
                    var path = '/pages/openkf/openkf?url=' + encodeURIComponent(link) + '&id=' + id;
                    if (link && id) {
                        uni.openCustomerServiceChat({
                            extInfo: {
                                url: link
                            },
                            corpId: id,
                            success(res) {
                                // console.log(res);
                            }
                        });
                    } else if (redirect) {
                        uni.redirectTo({
                            url: '/pages/redirect/index?url=' + encodeURIComponent(this.addUrlParam(url))
                        });
                    } else {
                        uni.navigateTo({
                            url: '/pages/redirect/index?url=' + encodeURIComponent(this.addUrlParam(url))
                        });
                    }
                    return false
                }
                /*携带tomini的原生路径，用于处理接口没有给原生路径，是h5和微信的结合
                 如：xxx.com?tomini=/pages/index*/
                if (url.includes('tomini')) {
                    let arr = url.split('?')[1].split('&');
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i].includes('tomini')) {
                            url = arr[i].replace('tomini=', '');
                            arr.splice(i, 1);
                            break;
                        }
                    }
                    url += `?${arr.join('&')}`;
                }

                // 跳转第三方小程序
                if (url.indexOf('wxMiniprogram://') > -1) {
                    var ahref = url.replace('wxMiniprogram://', '');
                    var miniId = ahref.split('?/')[0];
                    var //小程序原始id
                        path = ahref.split('?/')[1]; //跳转的路径
                    var _ghId = miniId.split('/')[0];
                    var _appid = miniId.split('/')[1];
                    var _path = path ? '/' + path : '';
                    uni.navigateToMiniProgram({
                        appId: _appid,
                        path: _path,
                        success(res) {
                            // wx.navigateBack();
                        },
                        fail(res) {
                            uni.showToast({
                                title: res,
                                icon: 'success',
                                duration: 2000
                            });
                        }
                    });
                }
                //传统跳转，如果redirectb是true则用redirect方式跳转
                if (redirectb) {
                    uni.redirectTo({
                        url: url.indexOf('http') == 0 ? '/pages/redirect/index?url=' +
                            encodeURIComponent(this.addUrlParam(url)) : decodeURIComponent(url)
                    });
                } else {
                    uni.navigateTo({
                        url: url.indexOf('http') == 0 ? '/pages/redirect/index?url=' +
                            encodeURIComponent(this.addUrlParam(url)) : decodeURIComponent(url)
                    });
                }

            }
        }
    },
    tologin(path, redirect = false) {
        let url;
        if (!path) { //当前页面路径
            let curPage = getCurrentPages();
            let route = curPage[curPage.length - 1].$page.fullPath; //获取当前页面的路由
            // && this.globalData.platForm == 'web' 这个判断是为了避免小程序中登录成功之后跳转404
            path = `${this.globalData.loginMode == 1 && this.globalData.platForm == 'web' ? this.globalData.masterDomain : ''}${route}`;
        }
        path = decodeURIComponent(path).replace('?', 'huoniaowh').replace(/&/g, 'huoniaolg').replace(/=/g,
            'huoniaodh'); //符号替换，如果path中直接用'?'、'&'、'='会被抹掉
        // path = decodeURIComponent(path).replace('?', 'loginwh').replace(/&/g, 'loginlg').replace(/=/g,
        // 	'logindh'); //符号替换，如果path中直接用'?'、'&'、'='会被抹掉
        if (this.globalData.platForm == 'web') {
            url = `${this.globalData.masterDomain}/login.html`
            if (this.globalData.appBoolean && !window.Android) {
                window.isCheckLogin = true;
                window.checkUserid()
            }
        } else if (this.globalData.loginMode == 1) { //H5
            url =
                `${this.globalData.masterDomain}/login.html?from=wxmini&wxMiniProgramLogin=1&forcelogout=1&path=${encodeURIComponent(path)}`;
        } else { //原生
            url = `/pages/login/index?wxMiniProgramLogin=1&back=1&path=${encodeURIComponent(path)}`;
        }
        this.linkTo(url, redirect);
    },
    openMap({
        lat = 0,
        lng = 0,
        address = '',
        title = '',
    }) {
        if (this.globalData.platForm == 'mp-weixin') { //微信
            uni.openLocation({
                latitude: Number(lat),
                // 纬度，范围为-90~90，负数表示南纬
                longitude: Number(lng),
                // 经度，范围为-180~180，负数表示西经
                scale: 14,
                // 缩放比例
                address: address
            });
        } else if (this.globalData.platForm == 'web') {
            if (this.globalData.webWeixin) { //微信自带的浏览器
                if (window.site_map == "baidu") {
                    let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
                    let x = lng - 0.0065;
                    let y = lat - 0.006;
                    let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
                    let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
                    lng = z * Math.cos(theta);
                    lat = z * Math.sin(theta);
                }
                window.jWeixin.openLocation({
                    name: title, // 位置名
                    address: address, // 地址详情说明
                    latitude: Number(lat), // 纬度，浮点数，范围为90 ~ -90
                    longitude: Number(lng), // 经度，浮点数，范围为180 ~ -180。
                    scale: 14, // 地图缩放级别,整型值,范围从1~28。默认为最大
                })
            } else if (this.globalData.appBoolean) { //app
                window.setupWebViewJavascriptBridge(function (bridge) {
                    bridge.callHandler("skipAppMap", {
                        "lat": lat,
                        "lng": lng,
                        "addrTitle": title,
                        "addrDetail": address
                    }, function (responseData) { });
                });
            } else { //普通浏览器
                let url = this.getMapUrl({
                    title: title,
                    address: address,
                    lat: Number(lat),
                    lng: Number(lng),
                    cityName: this.globalData.cityInfo.name,
                    mapType: window.site_map,
                    mapKey: window.site_map_key
                });
                this.linkTo(url);
            }
        }
    },
    previewImage(data) {
        if (this.globalData.platForm == 'web') { //H5
            if (this.globalData.appBoolean && window.Android) { //app
                window.setupWebViewJavascriptBridge(function (bridge) {
                    bridge.callHandler(
                        'previewImage', data.app,
                        function (responseData) { }
                    );
                });
            } else if (this.globalData.webWeixin) { //微信浏览器
                window.jWeixin.previewImage(data.app);
            } else { //普通浏览器
                uni.previewImage(data.init);
            }
        } else { //小程序
            uni.previewImage(data.init);
        }
    },
    iosShare({
        title = '',
        litpic = '',
        description = '',
        shareShow = false //与系统类型无关，这个值为true就显示分享按钮（ios和Android）
    }) {
        if (this.globalData.appBoolean && (shareShow || !this.globalData.appFullScreen)) {
            let url = window.location.href;
            let fromShare = this.globalData.userid ? 'fromShare=' + this.globalData.userid : '';
            let link = `${url}${url.includes('?') ? '&' : '?'}${fromShare}`;
            window.setupWebViewJavascriptBridge(function (bridge) {
                let initAppConfigData = {
                    "apptitle": '', //为空时不改变现有标题
                    "share": 1, //为1时显示分享按钮
                    "report": 1, //为1时显示举报按钮
                    "shareContent": {
                        "platform": "all",
                        "url": link,
                        "title": title,
                        "imageUrl": litpic,
                        "summary": description
                    }
                }
                bridge.callHandler("initAppConfig", {
                    'value': initAppConfigData
                }, function (responseData) { });
                bridge.callHandler("getAppInfo", {}, function (responseData) { });
            })
        }
    },
    posterProcess(str) {
        let newStr = String(str);
        newStr = newStr.replace(/<br([^>]*)>/g, '').replace(/\\n/g, ''); //去掉<br>和<br/>标签和换行符
        let targetArr = []; //最终的配置
        let nodeArr = ['div', 'p', 'span', 'img', 'video']; //可能出现的元素标签
        let nalength = nodeArr.length;
        for (let i = 0; i < nalength; i++) {
            let item = nodeArr[i];
            let eleRule;
            if (item == 'img') {
                eleRule = new RegExp(`<img((?!\/>).)*\/>`, 'g'); //获取对应标签
            } else {
                eleRule = new RegExp(`<${item}((?!<\/${item}>).)*<\/${item}>`, 'g');
            }
            let nodeLabel = newStr.match(eleRule); //获取对应标签
            if (!nodeLabel) {
                continue;
            }
            for (let j = 0; j < nodeLabel.length; j++) { //遍历标签
                let nodes = nodeLabel[j];
                let bool = blankDel(item, nodes); //是否有清除的空标签
                if (bool) { //跳过此次循环
                    continue;
                }
                let index = newStr.indexOf(`<${item}`); //查找首次出现的下标
                let rule = new RegExp(`<${item}([^>]*)>`);
                newStr = newStr.replace(rule, ''); //去掉之后再次查找
                let testNodes = nodes.replace(rule, ''); //去掉之后再次查找
                if (!(testNodes.includes('<div') || testNodes.includes('<p') || testNodes.includes('<span') ||
                    testNodes.includes('<img') || testNodes.includes('<video'))) { //里面已经没有嵌套节点了
                    if (item == 'video') {
                        let src = nodes.match(/src="(\S*)"/);
                        let posterSrc = nodes.match(/poster="(\S*)"/);
                        targetArr[index] = {
                            type: 'video',
                            value: src ? src[1] : '',
                            poster: posterSrc ? posterSrc[1] : this.globalData.imgError
                        };
                    } else if (item == 'img') {
                        let src = nodes.match(/src=[\]["](\S*)["]/);
                        targetArr[index] = {
                            type: 'image',
                            value: src ? src[1] : this.globalData.imgError
                        };
                    } else {
                        let textRule = new RegExp(`([\\s\\S]*)<\/${item}>`);
                        targetArr[index] = {
                            type: 'text',
                            value: testNodes.replace(/&nbsp;/g, '').match(textRule)[1]
                        };
                    }
                }
            }
        }

        function blankDel(item, elements) { //去掉空标签
            let blankRule = new RegExp(`<${item}([^>]*)>([\\s\\S]*)<\/${item}>`);
            let reg = (str) => str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
            let eleRule = new RegExp(`${reg(elements)}`, 'g');
            let matchRes = elements.match(blankRule);
            if (matchRes && matchRes.length > 2 && !matchRes[2]) {
                str = str.replace(eleRule, ''); //清掉原始字符串中的空标签
                return true;
            } else {
                return false;
            }
        }
        return targetArr.filter(Boolean); //去空
    },
    getMapUrl(pageData) {
        let OpenMap_URL = '';
        if (pageData.mapType == "baidu") {
            OpenMap_URL =
                `https://api.map.baidu.com/marker?location=${pageData.lat},${pageData.lng}&title=${encodeURIComponent(pageData.title)}&content=${encodeURIComponent(pageData.address)}&output=html`
        } else if (pageData.mapType == "google") {
            OpenMap_URL =
                `https://maps.google.com/?q=${pageData.lat},${pageData.lng}&g=${encodeURIComponent(pageData.address)}+${encodeURIComponent(pageData.cityName)}`
        } else if (pageData.mapType == "amap") {
            OpenMap_URL =
                `https://uri.amap.com/marker?position=${pageData.lng},${pageData.lat}&name=${encodeURIComponent(pageData.title)}`
        }
        return OpenMap_URL
    },
    isValidTimestamp: function (timestamp) {
        timestamp = timestamp * 1;
        return Number.isFinite(timestamp) && timestamp > 0;
    },
    dateFormatter: function (timestamp) {
        var cfg_timezone = this.globalData.appConfig ? this.globalData.appConfig.cfg_timeZoneName : '';
        var cfg_timezoneOff = this.globalData.appConfig ? this.globalData.appConfig.cfg_timeZone : 0; //时差
        if (!this.isValidTimestamp(timestamp)) return {
            year: '-',
            month: '-',
            day: '-',
            hour: '-',
            minute: '-',
            second: '-'
        };

        // 创建一个新的Date对象，使用时间戳
        let offHour = new Date(timestamp * 1000).getTimezoneOffset() / 60;
        offHour = 0 - offHour;
        let date = new Date(timestamp * 1000);
        if (typeof Intl == 'undefined') {
            date = new Date((timestamp * 1 + (cfg_timezoneOff - offHour) * 3600) * 1000);
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            month = month > 9 ? month : ('0' + month)
            let day = date.getDate();
            day = day > 9 ? day : ('0' + day)
            let hour = date.getHours();
            hour = hour > 9 ? hour : ('0' + hour)
            let minute = date.getMinutes();
            minute = minute > 9 ? minute : ('0' + minute)
            let second = date.getSeconds();
            second = second > 9 ? second : ('0' + second)
            return {
                year: year,
                month: month,
                day: day,
                hour: hour,
                minute: minute,
                second: second
            };
        } else {
            // 使用Intl.DateTimeFormat来格式化日期
            const dateTimeFormat = new Intl.DateTimeFormat('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false,
                timeZone: !cfg_timezone ? "Asia/Shanghai" : cfg_timezone, //指定时区，cfg_timezone变量已在页面中通过程序自动声明
            });
            // 获取格式化后的时间字符串
            const formatted = dateTimeFormat.format(date);
            // 将格式化后的字符串分割为数组
            const [year, month, day, hour, minute, second] = formatted.match(/\d+/g);
            // 返回一个对象，包含年月日时分秒
            return {
                year,
                month,
                day,
                hour,
                minute,
                second
            };
        }

    },
    transTimes: function (timestamp, n) {
        const dateFormatter = this.dateFormatter(timestamp);
        const year = dateFormatter.year;
        const month = dateFormatter.month;
        const day = dateFormatter.day;
        const hour = dateFormatter.hour;
        const minute = dateFormatter.minute;
        const second = dateFormatter.second;
        if (n == 1) {
            return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
        } else if (n == 2) {
            return year + '-' + month + '-' + day;
        } else if (n == 3) {
            return month + '-' + day;
        } else {
            return 0;
        }
    },
    timestampToTime(timestamp, {
        Y = 1,
        M = 1,
        D = 1,
        h = 1,
        m = 1,
        s = 1
    }, str = '-') {
        //时间戳为秒需*1000，时间戳为毫秒的话不需乘1000
        timestamp = String(timestamp); //如果传过来的是数字类型的会出问题，这里转一下
        let date = new Date(timestamp.length < 13 ? timestamp * 1000 : timestamp);
        let year = ''; //年
        let month = ''; //月
        let day = ''; //日
        let hour = ''; //小时
        let minutes = ''; //分钟
        let seconds = ''; //秒
        const dateFormatter = this.dateFormatter(timestamp.length < 13 ? timestamp : parseInt(timestamp / 1000))
        if (Y) {
            year = dateFormatter.year + str;
        }
        if (M) {
            month = dateFormatter.month + str;
        }
        if (D) {
            day = dateFormatter.day + (h ? ' ' : '')
        }
        if (h) {
            hour = dateFormatter.hour + ':';
        }
        if (m) {
            minutes = dateFormatter.minute + (s ? ':' : '');
        }
        if (s) {
            seconds = dateFormatter.second;
        }
        return `${year}${month}${day}${hour}${minutes}${seconds}`;
    },
    loginCheck(url, redirect = false) {
        this.globalData.userid = uni.getStorageSync('userid')
        if (this.globalData.platForm == 'web') { // H5端可能没有本地存储
            let loginInfo = window.$.cookie('HN_login_user');
            if (loginInfo) { //表示已登录
                this.globalData.userid = window.$.cookie('HN_userid') || window.loginUserId || uni.getStorageSync('userid');
            } else { //表示未登录 需要清空缓存
                this.globalData.userid = '';
                uni.removeStorageSync('userid')
            }
        }else if(this.globalData.platForm == 'mp-weixin' || this.globalData.platForm == 'mp-toutiao'){
            let access_token = uni.getStorageSync('access_token');
            let refresh_token = uni.getStorageSync('refresh_token');
            if(!access_token || !refresh_token){ // 没有登录的token 会导致个人中心部分操作 提示登录超时    因此没有token需要判定为未登录
                this.globalData.userid = ''
            }
        }
        if (!this.globalData.userid) {
            uni.removeStorageSync('userid')
            if (this.globalData.platForm == 'web') {
                location.href = `${this.globalData.masterDomain}/login.html`;
            } else {
                this.tologin(url, redirect);
            }
        }
        return Boolean(this.globalData.userid);
    },
    showErr(tip) {
        uni.hideLoading();
        uni.showModal({
            title: '提示',
            content: tip,
            showCancel: false,
        })
    },
    biasTop(element, _this) {
        let systemInfo = uni.getSystemInfoSync();
        if (systemInfo.platform == 'windows') { //pc端小程序
            _this.biasTop = 0;
            this.globalData.biasTop_88 = 0;
            return false;
        }
        var info = uni.getMenuButtonBoundingClientRect();
        let tem = setInterval(() => { //该定时器保证一定能够获取到该元素
            let query = uni.createSelectorQuery().in(_this);
            query.select(element).boundingClientRect((rect) => {
                if (rect && rect.height) {
                    _this.biasTop = -(rect.height - info.height) / 2 - (this.globalData.navTop -
                        info.top);
                    this.globalData.biasTop_88 = _this.biasTop;
                    clearInterval(tem);
                    console.log('顶部偏差：', _this.biasTop);
                }
            }).exec();
        }, 10)
    },
    getdomFn(pageThis, element, fn) {
        /* 	__this:页面的this (必传)
            element:节点id/类名，可获取多个，如：‘.top,#bottom’ (必传)
            fn(value):回调函数value是回调值
        */
        pageThis.$nextTick(res => {
            let query = uni.createSelectorQuery().in(pageThis);
            query.selectAll(element).boundingClientRect(res => {
                fn(res); //回调
            }).exec();
        })
    },
    getdomComposition(proxy, element) {
        return new Promise((resolve, reject) => {
            let query = uni.createSelectorQuery().in(proxy);
            query.selectAll(element).boundingClientRect(res => {
                resolve(res);
            }).exec();
        })
    },
   
    useOtherPhoneNumber(tt, data) {
        var dataset = data.currentTarget.dataset;
        if (!data.detail.encryptedData && !data.detail.iv) {
            uni.showToast({
                title: '已拒绝小程序授权',
                icon: 'none',
                duration: 2000
            });
            return false;
        }
        uni.login({
            success: res => {
                let phoneData = {
                    code: res.code,
                    encryptedData: data.detail.encryptedData,
                    iv: data.detail.iv
                };
                this.callPhone(tt, '', dataset, phoneData);
            }
        });
    },
    getFonts(fontName, url) {
        uni.loadFontFace({
            family: fontName,
            source: 'url("' + url + '")',
            success: function (res) {
                console.log(res.status);
            },
            fail: function (res) {
                console.log(res.status);
            },
            complete: function (res) {
                console.log(res.status);
            }
        });
    },
    cachePage(indexName, __this) {
        let cacheData = uni.getStorageSync(indexName);
        let cacheCity = cacheData.cityId;
        if (cacheCity && cacheCity == this.globalData.cityInfo.cityid) { //分站未切换，加载缓存，其他情况直接清掉
            for (let key in cacheData) {
                __this[key] = cacheData[key];
            }
        } else {
            cacheData = {};
            uni.setStorageSync(indexName, {});
        }
        __this['cacheData'] = cacheData; //缓存数据
    },
    confirmLoaction(templates) {
        return new Promise(resolve => {
            if (this.globalData.platForm == 'web') { //H5
                let cityUrl =
                    `${this.globalData.masterDomain}/changecity.html?currentPageOpen=1&backModule=${templates}`;
                let newCity = JSON.parse(window.$.cookie('HN_siteCityInfo'));
                if (newCity) {
                    window.cityInfo = newCity;
                    this.globalData.cityInfo = newCity;
                    resolve(newCity);
                } else {
                    this.linkTo(cityUrl);
                }
            } else { //小程序
                let cityUrl = `/pages/changeCity/index?module=${templates}`;
                let mini = uni.getStorageSync('cityInfo');
                if (mini) {
                    this.globalData.cityInfo = mini;
                    resolve(mini);
                } else {
                    this.linkTo(cityUrl);
                }
            }
        })
    },
    drawAdv(pageThis, advData, eleId) {
        let adv = advData;
        let advId = eleId;
        window.TencentGDT.NATIVE.renderAd(adv, advId); //渲染广告
        // 曝光上报
        window.TencentGDT.NATIVE.doExpose({
            container: advId,
            advertisement_id: adv.advertisement_id,
            placement_id: adv.placement_id,
            traceid: adv.tid,
        });
        // 点击上报
        let s_data = {
            "down_x": 0,
            "down_y": 0,
            "up_x": 0,
            "up_y": 0
        };
        pageThis.$nextTick(res => {
            $(`#${advId} iframe`)[0].contentDocument.onmousedown = function (event) {
                s_data['down_x'] = event.offsetX;
                s_data['down_y'] = event.offsetY;
            }
            $(`#${advId} iframe`)[0].contentDocument.onmouseup = function (event) {
                if ($(event.target).hasClass('del')) {
                    $(`#${advId}`).parent().hide();
                    return false;
                }
                s_data['up_x'] = event.offsetX;
                s_data['up_y'] = event.offsetY;
                window.TencentGDT.NATIVE.doClick({
                    s: encodeURIComponent(JSON.stringify(s_data)),
                    container: advId,
                    advertisement_id: adv.advertisement_id,
                    placement_id: adv.placement_id,
                    traceid: adv.tid,
                });
            }
        })
    },
    base64src(base64data, fun) {
        const base64 = base64data; //base64格式图片
        const time = new Date().getTime();
        const imgPath = uni.env.USER_DATA_PATH + "/poster" + time + "share" + ".png";
        //如果图片字符串不含要清空的前缀,可以不执行下行代码.
        const imageData = base64.replace(/^data:image\/\w+;base64,/, "");
        const file = uni.getFileSystemManager();
        file.writeFileSync(imgPath, imageData, "base64");
        fun(imgPath);
    },
    chatIntervalTime(originTime, selfConfig = {}) {
        /*使用说明：
            1、originTime：格式：时间戳（10位或者13位都行）或时间字符串
            2、selfConfig：数据类型是对象，对象值有这些：oneMinute、oneHour、oneDay、oneMonth、oneYear、oneMore，参考defaultConfig。
            3、defaultConfig中的type不用传，只用传set的值，内容为：condig、symbol、condition
            4、config和symbol分别对象方法timestampToTime中的第二个和第三个参数
            5、condition表示：若小于这个时间，则返回xx分钟前、xx天前，具体看改的是哪个配置中的condition。
                例：修改oneDay中，condition改成86400*3，表示若当前时间与目标时间差小于3天，就返回xx天前，其他同理，但要注意：type=more时，condition无效。
            6、如果selfconfig传了config且不为null，则传的condition无效。反之，除了type=more之外必传condition。
                注：condition不能乱设置，需遵循以下条件：
                onMinute.condition < oneHour.condition < oneDay.condition < oneMonth.condition < oneYear.condition < oneMore.condition
        */
        let _this = this;
        class timeConfig {
            //分割类型，值：minute、hour、day、week、month、year、more
            type = '';
            //当前时间和目标时间差值，单位秒
            Conditions = null;
            //timestampToTime的第二个和第三个参数
            timeChangeConfig = null;
            linkSymbol = '-';
            constructor(typeConfig, type) { //构造函数
                this.type = type;
                this.timeChangeConfig = typeConfig.config;
                this.linkSymbol = typeConfig.symbol;
                this.Conditions = typeConfig.condition;
            }
            operate() {
                let targetTime = String(originTime).length > 10 ? parseInt(originTime / 1000) : originTime; //起始时间
                let nowDate = parseInt(+new Date() / 1000);
                let type = this.type;
                if (type == 'more' || this.timeChangeConfig) { //超过今年或者有config定义
                    return _this.timestampToTime(targetTime, this.timeChangeConfig||{}, this.thislinkSymbol);
                } else if (nowDate - targetTime < this.Conditions) {
                    let returnText = '';
                    if (type == 'minute') { //n秒前
                        returnText = '刚刚'
                    } else if (type == 'hour') { //n分钟前
                        returnText = `${Math.floor((nowDate - targetTime) / 60)}分钟前`;
                    } else if (type == 'day') { //n小时前
                        returnText = `${Math.floor((nowDate - targetTime) / 3600)}小时前`;
                    } else if (type == 'month') { //n天前
                        returnText = `${Math.floor((nowDate - targetTime) / (24 * 3600))}天前`;
                    } else { //今年
                        returnText = _this.timestampToTime(targetTime, { Y: 0 }, this.linkSymbol);
                    }
                    return returnText;
                }
                return null
            }
        }
        //默认配置
        let defaultConfg = {
            oneMinute: { type: 'minute', set: { config: null, symbol: '-', condition: 60 } },
            oneHour: { type: 'hour', set: { config: null, symbol: '-', condition: 3600 } },
            oneDay: { type: 'day', set: { config: null, symbol: '-', condition: 86400 } },
            oneMonth: { type: 'month', set: { config: null, symbol: '-', condition: 604800 } },
            oneYear: { type: 'year', set: { config: null, symbol: '-', condition: 31536000 } },
            oneMore: { type: 'more', set: { config: null, symbol: '-', condition: null } }
        }
        for (let key in defaultConfg) {
            if (selfConfig[key]) {
                defaultConfg[key].set.config = selfConfig[key].config || null;
                defaultConfg[key].set.symbol = selfConfig[key].symbol || '-';
                defaultConfg[key].set.condition = selfConfig[key].condition || defaultConfg[key].condition;
            }
            let value = defaultConfg[key];
            let textValue = new timeConfig(value.set, value.type).operate();
            if (textValue) return textValue;//有返回值，直接结束循环
        }
    },
}